<template>
  <div>
    <!-- Main content -->
    <section class="content">
      <div class="table clearfix">
        <div class="addBrandDiv">
          <el-button type="primary" class="addBrand"  data-toggle="modal"
                     data-target="#modal-default" @click="addNewUser" v-if="$_has('sys:user:add')">新增用户</el-button>
        </div>
        <el-table
          ref="userlist"
          :data="userlist"
          tooltip-effect="dark"
          style="width: 100%;font-size:14px;"
          :header-cell-style="{background:'#F5F7FA',height:'60px','line-height':'60px',color:'#606266','font-size':'14px'}"
          @selection-change="handleSelectionChange">
          <el-table-column
            prop="username"
            label="用户名"
            min-width="10%"  align="center" >
          </el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            min-width="20%"  align="center" >
          </el-table-column>
          <el-table-column
            label="用户类型"
            min-width="10%"
            show-overflow-tooltip  align="center" >
            <template slot-scope="scope">
              {{getUserType(scope.row.flag)}}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            min-width="10%"
            show-overflow-tooltip  align="center" >
            <template slot-scope="scope">
              {{getUserStatus(scope.row.status)}}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            min-width="10%"  align="center" >
            <template slot-scope="scope">
              <div class="myicon-option">
                <i class="el-icon-myedit" title="编辑"  @click="getUserDetail(scope.row.userId)" data-toggle="modal"
                   data-target="#modal-default" v-if="$_has('sys:user:edit')"></i>
                <i :class="scope.row.status == 1 ? 'el-icon-disable' : 'el-icon-able'" :title="scope.row.status ==1 ? '禁用' : '启用'"
                   @click="editUserStatuCOmfirm(scope.row.userId,scope.row.status)"></i>
                <i v-show="userInfoShow(scope.row.phone)" class="el-icon-mydelete"  title="删除"  @click="deleteUserComfirm(scope.row.userId)"
                   v-if="$_has('sys:user:del')"></i>
                <i v-show="!userInfoShow(scope.row.phone)"  title="删除"> </i>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page" v-if="roleList.length != 0"
                       background
                       layout="total,prev, pager, next"
                       :total="pages.userPageList.total"
                       :pager-count="6"
                       :page-size="pages.userPageList.pageSize"
                       @current-change ='pagechange'
        >
        </el-pagination>
      </div>


      <div class="modal fade" id="modal-default">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title">{{action}}用户</h4>
            </div>
            <div class="modal-body">
              <form class="form-horizontal">
                <div class="box-body">
                  <div class="form-group">
                    <div class="col-sm-6 flex">
                      <label class="control-label min-width"><span class="sup">*</span>手机号：</label>
                      <div class="inline-block">
                        <input type="text" v-model ="username" class="form-control" placeholder="手机号">
                      </div>
                    </div>
                    <div class="col-sm-6 flex">
                      <label class="control-label min-width"><span class="sup">*</span>姓名：</label>
                      <div class="inline-block">
                        <input type="text" v-model="name" class="form-control" maxlength="40" placeholder="长度不超过40">
                      </div>
                    </div>
                  </div>
                  <div class="form-group">
                    <div class="col-sm-12 flex">
                      <span style="font-size: 14px;margin-left: 20px;color: #FF9328; padding-left:18px;">提示：新用户默认密码是123456</span>
                    </div>
                  </div>
                  <div class="box box-info">
                    <div class="box-header with-border bg-info">
                      <h3 class="box-title"><span class="sup">*</span>权限分配</h3>
                    </div>
                    <div class="box-body">
                      <el-checkbox-group v-model="roleIds">
                        <el-checkbox style="padding-right: 15px;padding-bottom: 15px;!important" v-for="wareHoseListItem in roleList" :key="wareHoseListItem.roleId" :label="wareHoseListItem.roleId">{{wareHoseListItem.roleName}}</el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </div>
                  <div class="box box-info" style="display: none">
                    <div class="box-header with-border bg-info">
                      <h3 class="box-title">指定仓库</h3>
                    </div>
                    <div class="box-body">
                      <el-checkbox-group v-model="whIds">
                        <el-checkbox style="padding-right: 15px;padding-bottom: 15px;!important" v-for="wareHoseListItem in wareHoseList" :key="wareHoseListItem.id" :label="wareHoseListItem.id">{{wareHoseListItem.name}}</el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </div>
                </div>

              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary"  @click="submitUser()">保存</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>

      <transition name="fade">
        <div v-if="errorShow" class="gritter-notice-wrapper " :class="{'success-notice-wrapper':errorClass}">
          <div id="gritter-item-4" class="gritter-item-wrapper gritter-error" style="" role="alert">
            <div class="gritter-item"><a class="gritter-close" tabindex="1" @click="closeError"><i
              class="fa fa-close"></i></a>
              <div class="gritter-without-image"><span class="gritter-title">{{errorTitle}}</span>
                <p>{{errorMsg}}</p></div>
            </div>
          </div>
        </div>
      </transition>
    </section>
    <!-- /.content -->
  </div>
</template>

<script>
  import {getCookie} from "../../../js/common/util";
  import instance from '@/api/index.js'
  import pagination from '@/components/common/pageComponent'

  export default {
    name: "userManagement",
    data() {
      return {
        roleIds:[],
        whIds:[],
        username:'',
        name:'',
        userId:'',
        userStatus: new Map(), //用户状态
        userEditStatus: new Map(), //用户启用禁用状态
        userlist: [],//用户列表
        userSubmitStatus:{}, //修改用户状态
        roleList:[],//角色列表
        toggle : [],//角色选中列表
        wareHoseList:[],//仓库列表
        userType: new Map(),//用户类型
        editUserDetail:{
          user:{
            username:'',
            name:'',
            userId:''
          },
          roleIds:[],
          whIds:[],
        }, //用户详情提交
        show: false,
        pages: {
          userPageList: {
            total: 0,
            pageNum: 1,
            pageSize: 10
          }
        },
        userFindParam: {},
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        errorShow: false,//错误显示
        errorMsg: '',//错误信息
        errorTitle: '',//错误提示标题
        errorClass: false,//错误样式
        action: "",
        userInfo: ""
      }
    },
    methods: {
      //获得当前选中数据
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      alertMessage: function (value) {
        if (value) {
          this.$message({
            showClose: false,
            message: '操作成功!',
            type: 'success'
          });
        } else {
          this.$message({
            showClose: false,
            message: '操作失败!',
            type: 'error'
          });
        }
      },
      //获取企业全部角色
      getRoleList : function(){
        let vm = this;
        instance.post('/role/getAllRole').then(function (data) {
          vm.roleList = data.data.data;
          console.log(vm.roleList)
          vm.show = false;//loading加载
        })
      },
      //获取企业仓库授权仓库
      getWareHousList : function(){
        let vm = this;
        vm.userDetail = [];
        instance.post('/v1/warehouse/getWareHouseNoPageList').then(function (data) {
          vm.wareHoseList = data.data.data;
          vm.show = false;//loading加载
        })
      },

      //定时信息提示
      setTime: function () {
        let vm = this;
        setTimeout(function () {
          vm.errorShow = false;
        }, 2500)
      },

      //关闭信息提示
      closeError: function () {
        this.errorShow = false;
      },

      //获取用户详情
      getUserDetail : function(_id){
        let vm = this;
        instance({
          method:'post',
          url:'/user/getUserDetail/' + _id
        }).then(function (data) {
          if(data.data.success){
            console.log(data)
            vm.username = data.data.data.username;
            vm.name = data.data.data.name;
            vm.userId = data.data.data.userId;
            vm.roleIds = [];
            vm.whIds = [];
            vm.action = "编辑";
            for (let i = 0; i < data.data.data.roleIds.length; i++){
              vm.roleIds.push(data.data.data.roleIds[i].roleId)
            }
            for (let j = 0; j < data.data.data.whIds.length; j++){
              vm.whIds.push(data.data.data.whIds[j].id)
            }
            console.log(vm.whIds)
          }else {
            vm.$message({
              showClose: false,
              message: data.data.msg,
              type: 'error'
            });
          }
        });
      },

      //添加用户
      addNewUser:function(){
        let vm = this;
        vm.username = '';
        vm.name = '';
        vm.userId = '';
        vm.roleIds = [];
        vm.whIds = ["wh1535340237168"];
        vm.action = "新增";
        vm.getWareHousList();
        vm.getRoleList();
      },

      //修改用户后保存用户或者创建用户
      submitUser : function(){
        let vm = this;
        let url = "";
        if (!vm.username) {
          vm.$alert('请输入手机号！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        //手机号验证
        var reg = /^[1][0-9]{10}$/;
        var r = reg.test(vm.username);
        if(!r) {
          vm.$alert('请输入正确的手机号！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        if (!vm.name) {
          vm.$alert('请输入用户姓名！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        if (vm.roleIds.length === 0) {
          vm.$alert('请选择权限！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        vm.editUserDetail.user.username = vm.username;
        vm.editUserDetail.user.name = vm.name;
        vm.editUserDetail.user.userId = vm.userId;
        vm.editUserDetail.roleIds = vm.roleIds;
        vm.editUserDetail.whIds = vm.whIds;
        if(vm.userId == ''){
          url ='/user/add';
        }else {
          url = '/user/editUser';
        }
        console.log(vm.editUserDetail)
        instance({
          method:'post',
          url:url,
          data:vm.editUserDetail
        }).then(function (data) {
          console.log(data);
          if(data.data.success){
            $("#modal-default").modal('hide');
          }
          vm.alertMessage(data.data.success);
          vm.getUserList();
        });
      },

      //修改用户状态
      editUserStatuCOmfirm:function(id,status){
        let vm = this;
        let str = '';
        if(status == 1){
          str = '禁用';
        }else if(status == 0){
          str = '启用';
        }
        vm.$confirm('此操作将'+str+'此用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          // instance.post('/v1/warehouse/updateWareHouse',vm.amendParam).then(function (data) {
          vm.editUserStatu(id,status)
          // vm.getUserList();
          // })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },
      //修改用户状态
      editUserStatu: function(id,status){
        let vm = this;
        vm.userSubmitStatus.userId = id;
        vm.userSubmitStatus.status = status == '1' ? '0':'1';
        instance.post('/user/editUserStatus',vm.userSubmitStatus).then(function (data) {
          vm.alertMessage(data.data.success);
          vm.getUserList();
        })
      },

      userInfoShow: function(phone){
        if(this.userInfo === phone){
          return false;
        } else {
          return true;
        }
      },
      //删除用户
      deleteUserComfirm:function(_id){
        let vm = this;
        vm.$confirm('此操作将删除此用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          vm.deleteUser(_id);
          vm.getUserList();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },
      //删除用户
      deleteUser: function(id){
        let vm = this;
        instance.post('/user/delteUser/'+id).then(function (data) {
          vm.alertMessage(data.data.success);
          vm.getUserList();
        })
      },
      //获取用户列表
      getUserList: function () {
        let vm = this;
        this.userFindParam.rows = vm.pages.userPageList.pageSize;
        instance.post('/user/getUserList',vm.userFindParam).then(function (data) {
          console.log(data)
          vm.userlist = data.data.data.list;
          vm.pages.userPageList = data.data.data;
          vm.show = false;//loading加载
        })
      },
      // 获取分页
      pagechange: function (currentPage, display) {
        this.userFindParam.page = currentPage;
        this.userFindParam.rows = display;
        this.pages.userPageList.pageNum = currentPage;
        this.getUserList();
      },
      //状态选择器方法
      getUserStatus: function (_key) {
        return this.userStatus.get(_key);
      },
      //用户状态启禁用状态
      getUserEditStatus: function (_key) {
        return this.userEditStatus.get(_key);
      },
      //用户类型
      getUserType: function (_key) {
        return this.userType.get(_key);
      },
    },

    //初始化方法
    created() {
      this.userInfo=getCookie("userName");
      console.log(this.userInfo)
      this.userStatus.set('1', '启用');
      this.userStatus.set('0', '禁用');
      this.userEditStatus.set('1', '禁用');
      this.userEditStatus.set('0', '启用');
      this.userType.set('1', '超级管理员');
      this.userType.set('0', '普通用户');
      this.getUserList();
      this.getRoleList();
      this.getWareHousList();
    },
    components: {
      pagination
    }
  }
</script>

<style scoped lang="less">
  .el-checkbox+.el-checkbox {
    margin-left: 30px;
  }
  //v2
  .content{
    .el-button {
      padding: 12px 20px;
    }
    .table{
      font-size: 14px;
      background: #fff;
      padding:20px;
      clear: both;
      overflow: hidden;
      .page{
        margin: 20px 0 5px;
        float: right;
      }
      .addBrandDiv{
        margin-bottom: 20px
      }

      .cell{
        display: flex;
        justify-content: center;
        align-items: center;
        .myicon-option{
          font-size: 18px;
          color: #409EFF;
          margin: 6px;
          cursor:pointer;

          i{
            display: inline-block;
            width: 18px;
            height: 18px;
            margin:  0 12px;
            &.el-icon-myedit{
              background:url('../../../assets/img/myEdit.png') no-repeat;
              background-size: 100%;
            }
            &.el-icon-disable{
              background:url('../../../assets/img/myDisable.png') no-repeat;
              background-size: 100%;
            }
            &.el-icon-able{
              background:url('../../../assets/img/myAble.png') no-repeat;
              background-size: 100%;
            }
            &.el-icon-mydelete{
              background:url('../../../assets/img/myDelete.png') no-repeat;
              background-size: 100%;
            }
          }
        }
      }
    }
  }
  //弹框
  #modal-default{
    .modal-dialog{
      border-radius: 4px;
      background: #fff;
      .modal-header{
        border-radius: 4px 4px 0 0;
        background: #fff;
      }
      .control-label {
        color: #606266;
        font-weight: normal;
        font-size: 14px;
      }
      .form-control{
        line-height: 40px;
        height: 40px;
        border-radius: 4px;
      }
      .box-header.with-border{
        border-radius: 4px 4px 0 0;
        border-bottom: 1px solid #E4E7ED;
      }
      .box-header{
        padding: 10px 10px 10px 0;
        margin: 0 20px;
        &::before{
          content: "";
          display: inline;
          height: 30px;
          width: 2px;
          background-color: #409EFF;
          position: absolute;
          left: -20px;
          top: 10px;
        }
      }
      .bg-info{
        background: none;
      }

      .box{
        border-top: none;
        box-shadow:none;
        border-radius: 4px;
        border: 1px solid #E4E7ED;
      }
      border-radius: 4px;

      .btn-primary:hover, .btn-primary:active, .btn-primary.hover{
        background: #409EFF;
      }
      .btn-primary{
        background: #409EFF;
        border-color: #409EFF;
        width: 68px;
        height: 40px;
        border-radius: 4px;
      }
      .box-body{
        padding-bottom: 0;
      }
      .modal-footer{
        border: none;
        text-align: center;
        padding-bottom: 40px;
      }
      .modal-footer .btn-default{
        width: 68px;
        height: 40px;
      }
    }
    .text-red {
      color: #FF5655!important;
    }
    .control-label{
      position: relative;
    }
    .sup{
      margin-right: 3px;
      color: #FF5655;
    }
  }


</style>

